package com.qifei.xmlg_backend.controller;

import com.qifei.xmlg_backend.DTO.announcement.AnnouncementQueryParam;
import com.qifei.xmlg_backend.entity.Announcement;
import com.qifei.xmlg_backend.entity.PageBean;
import com.qifei.xmlg_backend.entity.Result;
import com.qifei.xmlg_backend.service.IAnnouncementService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.net.openssl.ciphers.Authentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  公告管理控制器
 * </p>
 *
 * @author announcement
 * @since 2025-06-20
 */
@Slf4j
@RestController
@RequestMapping("/announcements")
@Api(tags = "公告管理接口")
public class AnnouncementController {

    @Autowired
    private IAnnouncementService announcementService;

    /**
     * 查询公告列表（分页）
     * @param param 查询参数
     * @param page 页码
     * @param pageSize 每页大小
     * @return 分页结果
     */
   @GetMapping("")
    @ApiOperation(value = "分页查询公告列表", notes = "管理员可查看所有公告，普通用户只能查看已发布的公告")
    public Result<?> getAnnouncementList(
           @ModelAttribute AnnouncementQueryParam param,
           @RequestParam(defaultValue = "1") @ApiParam("页码") Integer page,
           @RequestParam(defaultValue = "10") @ApiParam("每页记录数") Integer pageSize,
           java.security.Principal principal) {
        
        // 获取当前用户的认证信息
        org.springframework.security.core.Authentication authentication = 
            org.springframework.security.core.context.SecurityContextHolder.getContext().getAuthentication();
        
        // 检查用户是否有ADMIN角色
        boolean isAdmin = authentication.getAuthorities().stream()
            .anyMatch(auth -> auth.getAuthority().equals("ROLE_ADMIN"));
        
        // 如果不是管理员，只能查看已发布的公告(status=1)
        if (!isAdmin) {
            param.setStatus((byte) 1); // 1表示已发布
            log.info("非管理员用户，只显示已发布公告");
        }
        
        param.setPage(page);
        param.setPageSize(pageSize);
        PageBean<Announcement> pageBean = announcementService.getAnnouncementList(param);
        return Result.success(pageBean);
   }

    /**
     * 通过id查询公告
     * @param id 公告ID
     * @return 公告详情
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "根据ID查询公告", notes = "所有用户都可以查看公告详情")
    public Result<?> getById(@PathVariable @ApiParam("公告ID") Long id) {
        Announcement announcement = announcementService.getById(id);
        return Result.success(announcement);
    }

    /**
     * 添加公告
     * @param announcement 公告信息
     * @return 操作结果
     */
    @PreAuthorize("hasAnyRole('ADMIN')")
    @PostMapping()
    @ApiOperation(value = "添加公告", notes = "需要管理员权限(role_admin)")
    public Result<?> add(@RequestBody @ApiParam("公告信息") Announcement announcement,
                        java.security.Principal principal) {
        // 直接从方法参数中获取认证用户
        String username = principal.getName();
        log.info("当前用户: " + username);
        announcement.setId(null);
        announcement.setAuthor(username);
        boolean success = announcementService.save(announcement);
        if (!success) {
            return Result.error("添加公告失败");
        }
        return Result.success("添加公告成功");
    }

    /**
     * 更新公告
     * @param announcement 公告信息
     * @return 操作结果
     */
    @PreAuthorize("hasAnyRole('ADMIN')")
    @PutMapping()
    @ApiOperation(value = "更新公告", notes = "需要管理员权限(role_admin)")
    public Result<?> update(@RequestBody @ApiParam("公告信息") Announcement announcement) {
        boolean success = announcementService.updateById(announcement);
        if (!success) {
            return Result.error("更新公告失败");
        }
        return Result.success("更新公告成功");
    }

    /**
     * 删除公告
     * @param ids 公告ID，多个ID用逗号分隔
     * @return 操作结果
     */
    @PreAuthorize("hasAnyRole('ADMIN')")
    @DeleteMapping("/{ids}")
    @ApiOperation(value = "删除公告", notes = "需要管理员权限(role_admin)，支持批量删除，多个ID用逗号分隔")
    public Result<?> delete(@PathVariable @ApiParam("公告ID，多个ID用逗号分隔") String ids) {
        String[] idArray = ids.split(",");
        if (idArray.length == 1) {
            // 单个删除
            boolean removed = announcementService.removeById(Long.valueOf(idArray[0]));
            return removed ? Result.success("删除成功") : Result.error("删除失败");
        }
        List<Long> idList = Arrays.stream(ids.split(",")).map(Long::valueOf).toList();
        boolean removed = announcementService.removeByIds(idList);
        if (removed) {
            return Result.success("批量删除成功");
        } else {
            return Result.error("批量删除失败");
        }
    }

    /**
     * 更新公告状态
     * @param id 公告ID
     * @param status 状态值
     * @return 操作结果
     */
    @PreAuthorize("hasAnyRole('ADMIN')")
    @PutMapping("/{id}/status/{status}")
    @ApiOperation(value = "更新公告状态", notes = "需要管理员权限(role_admin)，0-草稿，1-已发布，2-已撤回")
    public Result<?> updateStatus(
            @PathVariable @ApiParam("公告ID") Long id,
            @PathVariable @ApiParam("状态值") Byte status) {
        Announcement announcement = announcementService.getById(id);
        if (announcement == null) {
            return Result.error("公告不存在");
        }
        announcement.setStatus(status);
        boolean success = announcementService.updateById(announcement);
        if (!success) {
            return Result.error("更新状态失败");
        }
        return Result.success("更新状态成功");
    }
}
